var createError = require('http-errors');  //http 异常
var express = require('express');   //express 库
var path = require('path');   //path Node 自带的 API 处理路径的
var cookieParser = require('cookie-parser');    //编译cookies
var logger = require('morgan');   //日志记录

require("./utils/connect");   // 链接数据库 
require("./utils/server");

//全局的服务器配置文件

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commentRouter = require('./routes/comment');
var vueRouter = require('./routes/vue');
var schoolRouter = require('./routes/school');
var cors = require('cors');

var app = express();    //全局的express对象
app.use(cors());  // 解决跨域  
var session = require("express-session")

// view engine setup
app.set('views', path.join(__dirname, 'views'));   //拼接  __dirname  根路径  views===/
app.set('view engine', 'ejs');  // 试图加载 引擎  ejs （Jade handlerBars artTempalte smart）

app.use(logger('dev'));   //开发环境的日志记录
app.use(express.json());  // post 请求的参数  
app.use(express.urlencoded({ extended: false }));   //接受post请求  发送的参数  req.body
app.use(cookieParser());  //设置一个cookies编译
app.use(express.static(path.join(__dirname, 'public')));  //express.static 静态目录  public===/

app.use(session({
  secret: '12345',
  name: 'name',
  cookie: { maxAge: 2 * 3600 * 1000 },  // 2h 
  resave: false,
  saveUninitialized: true
}));


app.use('/', indexRouter);    //设置一个路由对象
app.use('/users', usersRouter);   //users 路由别名
app.use('/comment', commentRouter)   //comment 路由别名
app.use('/vue', vueRouter)   //vue 路由别名
app.use('/school', schoolRouter)   //school 路由别名

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


app.locals.forMat = function (date) {
  var time = new Date(date);
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var day = time.getDate();
  var hour = time.getHours();
  var min = time.getMinutes();
  var sec = time.getSeconds();
  return `${year}-${month > 9 ? month : `0${month}`}-${day > 9 ? day : `0${day}`} ${hour > 9 ? hour : `0${hour}`}:${min > 9 ? min : `0${min}`}:${sec > 9 ? sec : `0${sec}`}`
}


module.exports = app;
